;
//设置cookie
function setCookie(name, value, exdays, domain) {
    let d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    let expires = "expires="+d.toUTCString();
    let cookies = name + "=" + value + "; " + expires+"; path=/";//path=/是根路径

    if(domain){
        cookies = cookies + ';domain=' + domain
    }

    document.cookie = cookies
}

// 获取cookie
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        if (name === 'userId') {
            return Number(unescape(arr[2]));
        } else {
            return unescape(arr[2]);
        }
    } else {
        return null;
    }
}

// 删除cookie
function clearCookie(name) {
  setCookie(name, "", -1);
}


let ajax = function (options) {

    let token = getCookie('accessToken')

    if (!token) {
      if (window.location.href.indexOf('register') > -1) {

      } else {
        window.location.href = '../../register/login.html'
      }
    }


    let setting = {
        url: '',
        type: 'GET',
        dataType: 'json',
        beforeSend: function (request) {
            if (!token && window.location.href.indexOf('register') > -1) {

            } else {
                request.setRequestHeader("accessToken", token);
            }
        },
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            console.log(data)

        },
        error: function (err) {
            console.log(err)
        },
        complete: function (XHR, TS) {
            if (XHR.responseText) {
                let data = JSON.parse(XHR.responseText)
                if (data.errorCode === '1906') {
                    clearCookie('accessToken')
                    localStorage.removeItem('userInfo')
                    window.location.href = '../../register/login.html'
                }
            }
        }
    };

    $.extend(setting, options);

    if (window.location.href.indexOf('laykj.cn') > -1) {
        setting.url = 'http://www.laykj.cn/wherebuyAPI/' + setting.url
    } else if (window.location.href.indexOf('http://192.168.0.6/') > -1) {
        setting.url = 'http://laykj.jiangda.info:8123/wherebuyAPI/' + setting.url 
    } else { 
        setting.url = 'http://laykj.jiangda.info:8123/wherebuyAPI/' + setting.url
    }

    let post = /post/ig;
    let put = /put/ig;
    if ((post.test(setting.type) || put.test(setting.type)) && setting.stringify !== false) {
        // setting.data = JSON.stringify(setting.data)
    }

    $.ajax(setting)
}

window.ajax = ajax


/**
 * 处理iOS 微信客户端6.7.4 键盘收起页面未下移bug
 */
;(/iphone|ipod|ipad/i.test(navigator.appVersion)) && document.addEventListener('blur', (e) => {
  // 这里加了个类型判断，因为a等元素也会触发blur事件
  ['input', 'textarea'].includes(e.target.localName) && document.body.scrollIntoView(false)
}, true)
